package view.backend.user;

import control.UserControl;
import exceptionManager.ExceptionManager;
import java.awt.Font;
import java.awt.event.*;
import java.sql.SQLException;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import model.User;
import model.handlers.UserHandler;
import utility.Security;
import view.generaldesign.DesignLayout;

/**
 * 
 * @author Sonny Sandberg
 */
public class AdminUserName 
{
    private JPanel
            leftPanel,
            adminUserNamePanel,
            newUserPanel;
    private AdminUser adminUser;
    private JTextField 
            tFieldString,
            tFieldEmail;
    private JPasswordField 
            pFieldPassword,
            pFieldPasswordRepeat;
    private JLabel lblPasswordMessage;
    private JButton btnConfirmAddUser;
    private int accessLevelAsInt;

    public AdminUserName(AdminUser view)
    {
        adminUser = view;
        
        leftPanel = new JPanel(null);
        leftPanel.setBounds(0, 0, 300, 500);
        leftPanel.setOpaque(false);
        
        adminUserNamePanel = new JPanel(null);
        adminUserNamePanel.setBounds(0, 0, 300, 80);
        adminUserNamePanel.setBorder(BorderFactory.createTitledBorder(DesignLayout.T_FIELD_RED, "Bruger", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, DesignLayout.STANDARD));
        adminUserNamePanel.setOpaque(false);
        
        newUserPanel = new JPanel(null);
        newUserPanel.setBounds(0, 90, 300, 300);
        newUserPanel.setBorder(DesignLayout.T_FIELD_RED);
        newUserPanel.setOpaque(false);
        
        buildNewUserPanel();
        
        JLabel lblName = new JLabel("Navn");
        lblName.setBounds(10, 25, 280, 18);
        lblName.setFont(DesignLayout.STANDARD.deriveFont(Font.BOLD, 12f));
        
        tFieldString = new JTextField();
        tFieldString.setBounds(10, 45, 280, 25);
        tFieldString.setBorder(DesignLayout.T_FIELD_RED);
        tFieldString.setBackground(DesignLayout.T_FIELD_BG_COLOR);
        tFieldString.setFont(DesignLayout.STANDARD);
        tFieldString.setHorizontalAlignment(SwingConstants.CENTER);
        tFieldString.addActionListener(new ActionListener() 
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                doLookUp();
                isUsernameAvailable();
                readyToAdd();
            }
        });
        
        adminUserNamePanel.add(lblName);
        adminUserNamePanel.add(tFieldString);
        
        leftPanel.add(adminUserNamePanel);
        leftPanel.add(newUserPanel);
    }
    
    private void buildNewUserPanel()
    {
        newUserPanel.removeAll();
        
        accessLevelAsInt = 1;
        
        JLabel lblPassword = new JLabel("Adgangskode");
        lblPassword.setBounds(10, 25, 280, 20);
        lblPassword.setFont(DesignLayout.STANDARD.deriveFont(Font.BOLD));
                
        pFieldPassword = new JPasswordField();
        pFieldPassword.setBounds(10, 50, 280, 25);
        pFieldPassword.setBorder(DesignLayout.T_FIELD_RED);
        pFieldPassword.setBackground(DesignLayout.T_FIELD_BG_COLOR);
        pFieldPassword.setFont(DesignLayout.STANDARD);
        pFieldPassword.setHorizontalAlignment(SwingConstants.CENTER);
        pFieldPassword.addKeyListener(new KeyAdapter() 
        {
            @Override
            public void keyReleased(KeyEvent e)
            {
                arePasswordsEqual();
                readyToAdd();
            }
        });
        
        JLabel lblPasswordRepeat = new JLabel("Gentag Adgangskode");
        lblPasswordRepeat.setBounds(10, 80, 280, 20);
        lblPasswordRepeat.setFont(DesignLayout.STANDARD.deriveFont(Font.BOLD));
        
        pFieldPasswordRepeat = new JPasswordField();
        pFieldPasswordRepeat.setBounds(10, 105, 280, 25);
        pFieldPasswordRepeat.setBorder(DesignLayout.T_FIELD_RED);
        pFieldPasswordRepeat.setBackground(DesignLayout.T_FIELD_BG_COLOR);
        pFieldPasswordRepeat.setFont(DesignLayout.STANDARD);
        pFieldPasswordRepeat.setHorizontalAlignment(SwingConstants.CENTER);
        pFieldPasswordRepeat.addKeyListener(new KeyAdapter() 
        {
            @Override
            public void keyReleased(KeyEvent e)
            {
                arePasswordsEqual();
                readyToAdd();
            }
        });
        
        JLabel lblEmail = new JLabel("Email");
        lblEmail.setBounds(10, 135, 280, 20);
        lblEmail.setFont(DesignLayout.STANDARD.deriveFont(Font.BOLD));
        
        tFieldEmail = new JTextField();
        tFieldEmail.setBounds(10, 160, 280, 25);
        tFieldEmail.setBorder(DesignLayout.T_FIELD_RED);
        tFieldEmail.setBackground(DesignLayout.T_FIELD_BG_COLOR);
        tFieldEmail.setFont(DesignLayout.STANDARD);
        tFieldEmail.setHorizontalAlignment(SwingConstants.CENTER);
        tFieldEmail.addKeyListener(new KeyAdapter() 
        {
            @Override
            public void keyReleased(KeyEvent e)
            {
                isEmailAvailable();
                readyToAdd();
            }
        });
        
        ActionListener actionListener =
        (
            new ActionListener() 
            {
                @Override
                public void actionPerformed(ActionEvent e)
                {
                    getUserAccessLevel(e);
                }
            }
        );
        
        ButtonGroup btnGroup = new ButtonGroup();
        
        JRadioButton rSalesman = new JRadioButton("Sælger", true);
        rSalesman.addActionListener(actionListener);
        rSalesman.setBounds(10, 190, 280, 20);
        rSalesman.setFont(DesignLayout.STANDARD);
        rSalesman.setOpaque(false);
        
        JRadioButton rAdmin = new JRadioButton("Admin");
        rAdmin.addActionListener(actionListener);
        rAdmin.setBounds(10, 215, 280, 20);
        rAdmin.setFont(DesignLayout.STANDARD);
        rAdmin.setOpaque(false);
        
        JRadioButton rDeveloper = new JRadioButton("Udvikler");
        rDeveloper.addActionListener(actionListener);
        rDeveloper.setBounds(10, 240, 280, 20);
        rDeveloper.setFont(DesignLayout.STANDARD);
        rDeveloper.setOpaque(false);
        
        btnGroup.add(rSalesman);
        btnGroup.add(rAdmin);
        btnGroup.add(rDeveloper);
        
        btnConfirmAddUser = new JButton("gem bruger");
        btnConfirmAddUser.setBounds(190, 265, 100, 25);
        btnConfirmAddUser.setBorder(DesignLayout.T_FIELD_RED);
        btnConfirmAddUser.setBackground(DesignLayout.T_FIELD_BG_COLOR);
        btnConfirmAddUser.setFont(DesignLayout.STANDARD.deriveFont(12f));
        btnConfirmAddUser.setEnabled(false);
        btnConfirmAddUser.setHorizontalAlignment(SwingConstants.CENTER);
        btnConfirmAddUser.addActionListener(new ActionListener() 
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                try
                {
                    String password = Security.encryptString(String.valueOf(pFieldPassword.getPassword()));
                    User user = new User(0, tFieldString.getText(), password, tFieldEmail.getText(), Security.createRandomString(255), accessLevelAsInt);
                    int added = UserControl.addUser(user);
                    if (added > 0)
                    {
                        newUserPanel.setVisible(false);
                        reset();
                        tFieldString.setText(user.getUsername());
                        doLookUp();
                    }
                } 
                catch (SQLException ex)
                {
                    ExceptionManager.handleSQLException(ex);
                } 
                catch (ClassNotFoundException ex)
                {
                    ExceptionManager.handleClassNotFoundException(ex);
                }                
            }
        });
        
        lblPasswordMessage = new JLabel("", JLabel.RIGHT);
        lblPasswordMessage.setBounds(10, 290, 160, 25);
        lblPasswordMessage.setFont(DesignLayout.STANDARD.deriveFont(11f));
        
        newUserPanel.add(lblEmail);
        newUserPanel.add(lblPassword);
        newUserPanel.add(lblPasswordRepeat);
        newUserPanel.add(lblPasswordMessage);
        newUserPanel.add(pFieldPassword);
        newUserPanel.add(pFieldPasswordRepeat);
        newUserPanel.add(tFieldEmail);
        newUserPanel.add(btnConfirmAddUser);
        newUserPanel.add(rSalesman);
        newUserPanel.add(rAdmin);
        newUserPanel.add(rDeveloper);
        
        newUserPanel.setVisible(false);
        newUserPanel.revalidate();
        newUserPanel.repaint();
    }
    
    private void getUserAccessLevel(ActionEvent e)
    {
        JRadioButton temp = (JRadioButton) e.getSource();
        if (temp.getText().equals("Sælger")) accessLevelAsInt = 1;
        if (temp.getText().equals("Admin")) accessLevelAsInt = 2;
        if (temp.getText().equals("Udvikler")) accessLevelAsInt = 3;
    }
    
    private boolean arePasswordsEqual()
    {
        boolean answer = false;
        
        if (
                String.valueOf(pFieldPassword.getPassword()).equals(String.valueOf(pFieldPasswordRepeat.getPassword())) &&
                String.valueOf(pFieldPassword.getPassword()).length() > 0
            )
        {
            lblPasswordMessage.setText("");
            answer = true;
        }
        else
        {
            lblPasswordMessage.setText("adgangskoder ikke ens");
            lblPasswordMessage.setForeground(DesignLayout.T_FIELD_BORDER_RED);
            answer = false;
        }
        return answer;
    }
    
    private boolean isEmailAvailable()
    {
        boolean answer = false;
        
        try
        {
            User tempUser = new User();
            tempUser.setEmail(tFieldEmail.getText());
            if (tempUser.getEmail().length() > 0)
            {
                answer = UserHandler.isEmailAvailable(tempUser);
                
                if (answer == false)
                {
                    lblPasswordMessage.setText("Email er allerede i brug");
                    lblPasswordMessage.setForeground(DesignLayout.T_FIELD_BORDER_RED);
                }
                else
                {
                    lblPasswordMessage.setText("");
                }
            }
        } 
        catch (SQLException ex)
        {
            ExceptionManager.handleSQLException(ex);
        } 
        catch (ClassNotFoundException ex)
        {
            ExceptionManager.handleClassNotFoundException(ex);
        }
        
        return answer;
    }
    
    private boolean isUsernameAvailable()
    {
        boolean answer = false;
        
        try
        {
            User tempUser = new User();
            tempUser.setUsername(tFieldString.getText());
            
            if (tempUser.getUsername().length() > 0)
            {
                answer = UserHandler.isUsernameAvailable(tempUser);
            }
            
            if (answer == true)
            {
                newUserPanel.setVisible(true);
            }
            else
            {
                newUserPanel.setVisible(false);
            }
        } 
        catch (SQLException ex)
        {
            ExceptionManager.handleSQLException(ex);
        } 
        catch (ClassNotFoundException ex)
        {
            ExceptionManager.handleClassNotFoundException(ex);
        }
        
        return answer;
    }
    
    public void reset()
    {
        tFieldString.setText("");
        tFieldEmail.setText("");
        pFieldPassword.setText("");
        pFieldPasswordRepeat.setText("");
        lblPasswordMessage.setText("");
    }
    
    public void doLookUp()
    {
        StringBuilder str = new StringBuilder();
        str.append("WHERE ");
        str.append("username LIKE '%"+tFieldString.getText()+"%'");
        adminUser.getAdminUserList().buildExistingScrollPanel(""+str, "ORDER BY id DESC", "");
    }
    
    private void readyToAdd()
    {
        if (isEmailAvailable() && isUsernameAvailable() && arePasswordsEqual() && accessLevelAsInt > 0)
        {
            btnConfirmAddUser.setEnabled(true);
        }
        else
        {
            btnConfirmAddUser.setEnabled(false);
        }
    }
    
    public JPanel getPanel()
    {
        return leftPanel;
    }
}